package com.techstar.ats.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import com.techstar.ats.dxp.live.rep.F09TrainIndicationInit;
import com.techstar.ats.dxp.live.rep.F10TrainIndicationUpdate;
import com.techstar.ats.dxp.live.rep.F11TrainIndicationRemove;

@Slf4j
@RequiredArgsConstructor
public class LiveService {
	private final JdbcTemplate jdbcTemplate;

	public void procInit(F09TrainIndicationInit init) {
		String deleteSql = "DELETE FROM train_online WHERE line=?";
		this.jdbcTemplate.update(deleteSql, init.line);
		init.indications.forEach(x -> save(init.line, x.global, x.group, x.train, x.devType.value(), x.devName, x.optTime));
	}

	public void procUpdate(F10TrainIndicationUpdate update) {
		save(update.line,
			update.indication.global,
			update.indication.group,
			update.indication.train,
			update.indication.devType.value(),
			update.indication.devName,
			update.indication.optTime);
	}

	public void procRemove(F11TrainIndicationRemove remove) {
		String deleteSql = "DELETE FROM train_online WHERE line=? AND train=?";
		this.jdbcTemplate.update(deleteSql, remove.line, remove.trainIdx);
	}

	private void saveByTrain(int line, String global, String group, String train, int devType, String devName, int optTime) {
		String selectSql = "SELECT train FROM train_online WHERE line=? AND train=?";
		this.jdbcTemplate.queryForObject(selectSql, String.class, line, train);
		String updateSql = "UPDATE train_online SET global_id=?,train=?,dev_type=?,dev_name=?,opt_time=? WHERE line=? AND train=?";
		this.jdbcTemplate.update(updateSql, global, train, devType, devName, optTime, line, train);
	}

	private void save(int line, String global, String group, String train, int devType, String devName, int optTime) {
		try {
			saveByTrain(line, global, group, train, devType, devName, optTime);
		} catch(EmptyResultDataAccessException var10) {
			String insertSql = "INSERT INTO train_online(line,global_id,group_id,train,dev_type,dev_name,opt_time) VALUES(?,?,?,?,?,?,?)";
			this.jdbcTemplate.update(insertSql, line, global, group, train, devType, devName, optTime);
		} catch(IncorrectResultSizeDataAccessException ex) {
			log.error(ex.getMessage());
		}
	}
}
